package com.douguo.recipe;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.douguo.recipe.manager.AppRuntime;
import com.douguo.recipe.manager.Registry;
import com.douguo.recipe.manager.SharedPreferencesManager;
import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetHomeCategories;
import com.douguo.recipe.network.GetHomeRecipes;
import com.douguo.recipe.network.GetHomeRecipes2;
import com.douguo.recipe.network.GetHotEkArticleList;
import com.douguo.recipe.network.GetSort;
import com.douguo.recipe.network.PrepareHomeCachePhoto;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipin;
import com.douguo.recipe.object.Caixi;
import com.douguo.recipe.object.EkArticle;
import com.douguo.recipe.object.HomeCategory;
import com.douguo.recipe.object.HomeRecipe;
import com.douguo.recipe.object.Kouwei;
import com.douguo.recipe.object.Nandu;
import com.douguo.recipe.object.Sort;
import com.douguo.recipe.object.Tese;
import com.douguo.recipe.provider.DBHelper;
import com.mobclick.android.MobclickAgent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;

public class LoadingActivity extends DouguoActivity {
	
	private static final String TAG = "DouguoActivity";

	private static final int ADD_SORT_SUCCESS = 1;

	private Thread mThread;
	private List<HomeCategory> mHomeCategories;
	
	private DouguoApplication mDouguoApplication;
	
	
	// -------------msg---------------
	

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// case Constant.GET_SORT:
			// List<Sort> sorts = (List<Sort>) msg.obj;
			// if (sorts != null) {
			// for (Sort sort : sorts) {
			// mDBHelper.addSort(sort);
			// }
			// Util.showShortToast(LoadingActivity.this,
			// R.string.initSortSuccess);
			//
			// }
			//
			// break;
			case Constant.MSG_HOT_CATEGORIES: 
				List<HomeCategory> categories = (List<HomeCategory>) msg.obj;
				if(categories != null && categories.size() > 0) {//获取成功
					mDouguoApplication.getAppRuntime().put(Constant.GLOBAL_HOT_MENU, categories);
				}
				break;
			case Constant.MSG_HOT_EK_ARTICLE:
				List<EkArticle> articles = (List<EkArticle>) msg.obj;
				if(articles != null && articles.size() > 0) {//获取成功
					mDouguoApplication.getAppRuntime().put(Constant.GLOBAL_EK_ARTICLES, articles);
				}
				break;
			case HomeActivity.MSG_HOME_RECIPES:
				List<HomeRecipe> recipes = (List<HomeRecipe>) msg.obj;
				if(recipes != null && recipes.size() > 0) {
					mDouguoApplication.getAppRuntime().put(Constant.GLOBAL_HOT_RECIPE, recipes);
				}
				break;
			case Constant.CLOSE_AND_START_ACTIVITY:
				if (!isFinishing()) {
					startActivity(new Intent(LoadingActivity.this,
							HomeActivity.class));
					if (msg.arg1 == ADD_SORT_SUCCESS) {
						Util.showLongToast(LoadingActivity.this,
								R.string.initSortSuccess);
					}
				}
				time= System.currentTimeMillis();
				Log.d(TAG, "3:"+time);
				finish();
				break;
			}
		}
	};

	private DBHelper mDBHelper;
	private static final int MAX_WAIT_TIME = 4000;

	long startTime;

	private long time;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loading);
		MobclickAgent.onError(this);
		time= System.currentTimeMillis();
		Log.d(TAG, "1:"+time);
		mDBHelper = new DBHelper(this);
		mDouguoApplication = (DouguoApplication) getApplication();
		
		initUI();
		initData();
		time= System.currentTimeMillis();
		Log.d(TAG, "2:"+time);
		
	}
	
	
	private void initUI() {

	}

	private void prepareData(boolean loadImg) {//提前下载，保存到内存，提高用户体验
		if(loadImg) {
			PrepareHomeCachePhoto.getHomePhoto();//提前下载第一章图片
		}
		GetHomeCategories.getHomeCategories(mHandler);//获取首页推荐分类
		GetHomeRecipes2.getHomeCaipuList(mHandler);//获取首页推荐分类
		GetHotEkArticleList.GetHotEkArticleList(mHandler);//获取ek热门文章
	}
	
	private void initData() {
		
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				Util.showLongToast(LoadingActivity.this, R.string.initingData);
				
			}
		}, 1000);
		
		
		Util.initNetwork(this);
		Util.readProxyAndPort(this);
		Util.updateNetworkType(this);
		if(Util.isConnected() && Util.isUseNetworkPreferences(this) && Util.isDownloadPhotoPreferences(this)){
			prepareData(true);
//			Log.d(TAG, "isConnected && usenework && load pic");
		}
		else if(Util.isConnected() && Util.isUseNetworkPreferences(this)){
			prepareData(false);
//			Log.d(TAG, "isConnected && usenework");
		}else {
			mDouguoApplication.getAppRuntime().clear();
//			Log.d(TAG, "without network");
		}
		
		
		mThread = new Thread(new Runnable() {
			
			public void run() {
				long startTime = System.currentTimeMillis();
				// check network
				// Util.updateNetworkType(LoadingActivity.this);
				int arg1 = 0;
				// check db
				if (!mDBHelper.hasSorts()) {
					// copy xml to database
					// GetSort.getSort(getResources().openRawResource(R.raw.defaultsort),
					// mHandler);
					// Log.d("test12",
					// String.valueOf(startTime
					// - System.currentTimeMillis()));

					List<Sort> sorts = (List<Sort>) onParsing(getResources()
							.openRawResource(R.raw.defaultsort));
					time= System.currentTimeMillis();
					Log.d(TAG, "5:"+time);

					if (sorts != null) {
						
						for (Sort sort : sorts) {
							mDBHelper.addSort(sort);
						}

						// Log.d("test12",
						// String.valueOf(startTime
						// - System.currentTimeMillis()));
						arg1 = ADD_SORT_SUCCESS;

					}
				}
				time= System.currentTimeMillis();
				Log.d(TAG, "4:"+time);
				long duration = System.currentTimeMillis() - startTime;
				long delay = MAX_WAIT_TIME - duration;
				if (delay < 0) {
					delay = 0;
				}
				
				mHandler.sendMessageDelayed(mHandler.obtainMessage(
						Constant.CLOSE_AND_START_ACTIVITY, arg1, 0), delay);

			}
		});
		mThread.start();

	}

	public Object onParsing(InputStream is) {

		XmlPullParser parser = Xml.newPullParser();
		List<Sort> sorts = null;
		Sort sort = null;
		boolean done = false;

		try {

			parser.setInput(is, null);
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT && !done) {
				String name = null;
				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					sorts = new ArrayList<Sort>();
					break;
				case XmlPullParser.START_TAG:
					name = parser.getName();
					if (name.equalsIgnoreCase("caixi")) {
						sort = new Caixi(parser.getAttributeValue(null, "id"),
								parser.getAttributeValue(null, "name"),
								parser.getAttributeValue(null, "order"),
								parser.getAttributeValue(null, "pic"));

						sorts.add(sort);

					} else if (name.equalsIgnoreCase("caipin")) {
						sort = new Caipin(parser.getAttributeValue(null, "id"),
								parser.getAttributeValue(null, "name"),
								parser.getAttributeValue(null, "order"),
								parser.getAttributeValue(null, "pic"));
						sorts.add(sort);

					} else if (name.equalsIgnoreCase("caipu")) {
						sort = new Tese(parser.getAttributeValue(null, "id"),
								parser.getAttributeValue(null, "name"),
								parser.getAttributeValue(null, "order"),
								parser.getAttributeValue(null, "pic"));
						sorts.add(sort);

					} else if (name.equalsIgnoreCase("nandu")) {
						sort = new Nandu(parser.getAttributeValue(null, "id"),
								parser.getAttributeValue(null, "name"),
								parser.getAttributeValue(null, "order"),
								parser.getAttributeValue(null, "pic"));
						sorts.add(sort);

					} else if (name.equalsIgnoreCase("kouwei")) {
						sort = new Kouwei(parser.getAttributeValue(null, "id"),
								parser.getAttributeValue(null, "name"),
								parser.getAttributeValue(null, "order"),
								parser.getAttributeValue(null, "pic"));
						sorts.add(sort);

					}

					break;

				case XmlPullParser.END_DOCUMENT:
					done = true;
					break;
				}
				eventType = parser.next();
			}
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sorts;
	}

}
